const tools = {
  // ArrayBuffer转16进制
  arrayBuffer2Hex(buffer) {
    const hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ("00" + bit.toString(16)).slice(-2);
      }
    );
    return hexArr.join("");
  },
  // 16进制转ArrayBuffer
  hex2buf(hexStr) {
    let count = hexStr.length / 2;
    let buffer = new ArrayBuffer(count);
    let dataView = new DataView(buffer);
    for (let i = 0; i < count; i++) {
      let curCharCode = parseInt(hexStr.substr(i * 2, 2), 16);
      dataView.setUint8(i, curCharCode);
    }
    return buffer;
  },
  // 十进制转十六进制
  dec2hex(dec, len) {
    //10进制转16进制补0
    let hex = "";
    while (dec) {
      let last = dec & 15;
      hex = String.fromCharCode((last > 9 ? 55 : 48) + last) + hex;
      dec >>= 4;
    }
    if (len) {
      while (hex.length < len) hex = "0" + hex;
    }
    return hex;
  },
  // 十六进制转十进制
  hex2int(hex) {
    let len = hex.length,
      a = new Array(len),
      code;
    for (let i = 0; i < len; i++) {
      code = hex.charCodeAt(i);
      if (48 <= code && code < 58) {
        code -= 48;
      } else {
        code = (code & 0xdf) - 65 + 10;
      }
      a[i] = code;
    }

    return a.reduce(function (acc, c) {
      acc = 16 * acc + c;
      return acc;
    }, 0);
  },
};

export default tools;
